package com.jf.blog.controller;

import com.jf.blog.service.KaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Api(tags = "验证码")
@Controller
public class KaptchaController {
    @Autowired
    private KaptchaService kaptchaService;

    @ApiOperation("获取验证码")
    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, @RequestParam String uuid) throws IOException {
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        BufferedImage bi = kaptchaService.getKaptcha(uuid);// 获取验证码图片
        ServletOutputStream out = response.getOutputStream();
        /*禁用缓存，可以解决部分同学电脑因为权限问题导致的500错误*/
        ImageIO.setUseCache(false);
        ImageIO.write(bi, "jpg", out);
    }
}
